/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 功能描述 配置使用ThreadPoolTaskExecutor 线程池
 *
 * @since 2022-03-08
 */
@Configuration
@EnableAsync
public class SpringThreadPoolExecutorConfig {
    // 核心线程
    @Value("${threadpool.core-pool-size}")
    private int corePoolSize;

    // 最大线程
    @Value("${threadpool.max-pool-size}")
    private int maxPoolSize;

    // 队列容量
    @Value("${threadpool.queue-capacity}")
    private int queueCapacity;

    // 线程最大空闲时间
    @Value("${threadpool.keep-alive-seconds}")
    private int keepAliveSeconds;

    /**
     * 线程池配置
     *
     * @return {@link ThreadPoolTaskExecutor}
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setKeepAliveSeconds(keepAliveSeconds);
        pool.setCorePoolSize(corePoolSize);
        pool.setMaxPoolSize(maxPoolSize);
        pool.setQueueCapacity(queueCapacity);

        // 队列满，线程被拒绝执行策略
        pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
        pool.setThreadNamePrefix("task-order-support-thread--");
        return pool;
    }
}